﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class CommodityLibController : BaseController
    {
        private readonly CommodityLibBLL _bll = new CommodityLibBLL();

        #region 列表

        public ActionResult List()
        {
            ViewBag.IsCreate = MagModules.FindAll(t => t
          .Action == "Create" && t
              .Controller == "CommodityBrand").Count > 0 ? 1 : 0;
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            var direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "CommodityName", "SuggestedPrice", "BrandName", "CategoryName", "Unit", "Spec", "IsVirtualStr", "IsBatchSaleStr" };
            var search = Request["search[value]"];
            var pageIndex = (start / length) + 1;

            var theList = _bll.GetPagingList(draw, pageIndex, length, SqlSafe(search), orderByColumns[order] + " " + direction);
            if (theList.data != null)
            {
                foreach (var item in theList.data)
                {
                    if (MagModules.FindAll(t => t
                        .Action == "Update" && t
                            .Controller == "CommodityLib").Count > 0)
                    {
                        item.Action += "<a class='btn btn-warning' href='javascript:;' onclick=updateData(" + item.Id +
                                      ");>修改</a> ";
                    }
                    if (MagModules.FindAll(t => t
                        .Action == "Delete" && t
                            .Controller == "CommodityLib").Count > 0)
                    {
                        item.Action += "<a class='btn btn-danger' href='javascript:;' onclick=deleteData(" + item.Id +
                                      ");>删除</a>";
                    }
                }
            }

            var jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        #endregion

        #region 创建
        public ActionResult Create()
        {
            InitiSet();
            var model = new CommodityLib { GiftEndTime = DateTime.Now };
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, CommodityLib model)
        {
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (!model.HasGiftCommodity)
            {
                model.GiftEndTime = DateTime.Now;
            }
            if (!model.IsLanmaSold)
            {
                model.DisplaySort = 0;
            }
            if (model.LowerPrice > 0)
            {
                if (model.SuggestedPrice < model.LowerPrice)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Conflict);
                }
            }
            if (model.CeilingPrice > 0)
            {
                if (model.SuggestedPrice > model.CeilingPrice)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Conflict);
                }
            }
            model.CommodityName = model.CommodityName.Trim();
            model.IsBatchSale = model.CommodityLibIdByBatch > 0;
            model.SupportPayWay = model.SupportPayWay.Trim(',');
            var strUploadImage = UploadImage("fileImage", "/CommodityLib/HeadPic/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage))
            {
                model.HeadPic = strUploadImage;
            }
            model.AddTime = DateTime.Now;
            var newId = _bll.Add(model);
            if (newId > 0)
            {
                if (model.IsLanmaSold)
                {
                    //平台售卖商品，强制入库到每家商店
                    var shopList = ShopsBLL.Instance.GetModelList();
                    var newShopCommodity = new ShopCommodity
                    {
                        CommodityLibId = newId,
                        SoldPrice = model.SuggestedPrice,
                        Quantity = 0,
                        DisplaySort = model.DisplaySort,
                        SellingStatus = true,
                        AddTime = DateTime.Now,
                        ShopCommission = model.ShopCommission
                    };
                    var shopIdList = new List<int>();
                    foreach (var item in shopList)
                    {
                        shopIdList.Add(item.Id);
                        if (shopIdList.Count % 2000 == 0)//每2000条执行一次
                        {
                            ShopCommodityBLL.Instance.AddList(shopIdList, newShopCommodity);
                            shopIdList = new List<int>();
                        }
                    }
                    if (shopIdList.Count > 0)
                    {
                        ShopCommodityBLL.Instance.AddList(shopIdList, newShopCommodity);
                    }
                }
                if (!string.IsNullOrEmpty(model.CouponArr))
                {
                    CommodityCouponGiftBLL.Instance.DeleteByCommodityLibId(model.Id);
                    string[] ids = model.CouponArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    foreach (string item in ids)
                    {
                        string[] couponArr = item.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                        int id = 0;
                        int quantity = 0;
                        if (!int.TryParse(couponArr[0], out id) || !int.TryParse(couponArr[1], out quantity)) continue;
                        if (quantity > 0)
                        {
                            CommodityCouponGiftBLL.Instance.Add(new CommodityCouponGift() { CouponId = id, Quantity = quantity, BelongToCommodityLibId = newId });
                        }
                    }
                }
                return RedirectToAction("List");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 修改
        public ActionResult Update(int id)
        {
            InitiSet();
            if (id <= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            CommodityLib model = _bll.GetModel(id);
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            if (model.CommodityLibIdByBatch > 0)
            {
                var batch = _bll.GetModel(model.CommodityLibIdByBatch);
                if (batch != null)
                    model.CommodityLibByBatchName = batch.CommodityName;
            }
            ViewBag.theHeadPic = ConfigurationManager.AppSettings["ImgFileSitePath"] + model.HeadPic;
            var couponCommodityLibList = CommodityCouponGiftBLL.Instance.GetModelList(string.Format("BelongToCommodityLibId={0}", id));
            couponCommodityLibList.ForEach(c =>
             {
                 model.CouponArr += c.CouponId + "|" + c.Quantity + ",";
                 var coupon = CouponBLL.Instance.GetModel(c.CouponId);
                 model.CouponNmaeArr += coupon != null ? coupon.CouponName + "/数量:" + c.Quantity + "," : "";
             });
            if (!string.IsNullOrEmpty(model.CouponNmaeArr))
            {
                model.CouponNmaeArr = "(" + model.CouponNmaeArr.Trim(',') + ")";
            }
            model.AreaInfo = AreaInfoBLL.Instance.GetModel(model.ProducingAreaId);
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(CommodityLib model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            model.CommodityName = model.CommodityName.Trim();
            if (!model.HasGiftCommodity) model.GiftEndTime = DateTime.Now;

            if (!model.IsLanmaSold)
            {
                model.DisplaySort = 0;
            }
            string strUploadImage = UploadImage("fileImage", "/CommodityLib/HeadPic/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage))
            {
                model.HeadPic = strUploadImage;
            }
            var checkModel = CommodityLibBLL.Instance.GetModel(model.Id);
            if (string.IsNullOrEmpty(model.CouponArr))
            {
                CommodityCouponGiftBLL.Instance.DeleteByCommodityLibId(model.Id);
            }
            if (checkModel.LowerPrice > 0)
            {
                if (model.SuggestedPrice < checkModel.LowerPrice)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Conflict);
                }
            }
            if (checkModel.CeilingPrice > 0)
            {
                if (model.SuggestedPrice > model.CeilingPrice)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.Conflict);
                }
            }

            model.IsBatchSale = model.CommodityLibIdByBatch > 0;
            model.SupportPayWay = model.SupportPayWay.Trim(',');
            if (_bll.Update(model))
            {
                if (checkModel.IsLanmaSold != model.IsLanmaSold)
                {
                    if (model.IsLanmaSold)//由非强制改为强制上架
                    {
                        //平台售卖商品，强制入库到每家商店
                        var shopList = ShopsBLL.Instance.GetModelList();
                        var shopCommodityList = ShopCommodityBLL.Instance.GetModelListWithOutIsDelete("CommodityLibId=" + model.Id);
                        var newShopCommodity = new ShopCommodity
                        {
                            CommodityLibId = model.Id,
                            SoldPrice = model.SuggestedPrice,
                            Quantity = 0,
                            DisplaySort = model.DisplaySort,
                            SellingStatus = true,
                            AddTime = DateTime.Now,
                            ShopCommission = model.ShopCommission
                        };
                        var shopIdList = new List<int>();
                        foreach (var item in shopList)
                        {
                            if (shopCommodityList.Count == 0 || shopCommodityList.Find(l => l.ShopId == item.Id) == null)
                            {
                                shopIdList.Add(item.Id);
                                if (shopIdList.Count % 2000 == 0) //每2000条执行一次
                                {
                                    ShopCommodityBLL.Instance.AddList(shopIdList, newShopCommodity);
                                    shopIdList = new List<int>();
                                }
                            }
                        }
                        if (shopIdList.Count > 0)
                        {
                            ShopCommodityBLL.Instance.AddList(shopIdList, newShopCommodity);
                        }
                        ShopCommodityBLL.Instance.UpdateShopCommodityByCommodityIds(model.Id.ToString(), model.SuggestedPrice, model.ShopCommission, model.DisplaySort);
                    }
                    else//由强制上架改为非强制
                    {
                        ShopCommodityBLL.Instance.DeleteByLanmaSoldCommodityIds(model.Id.ToString());
                    }
                    ShopCommodityBLL.Instance.UpdateDisplaySortByCommodityLibId(model.DisplaySort, model.Id);
                }
                //若为强制上架商品，则所有店铺价格同时需修改
                if (model.IsLanmaSold == true)
                {
                    ShopCommodityBLL.Instance.UpdateIsDeleteByCommodityLibId(model.Id);
                    if (checkModel.SuggestedPrice != model.SuggestedPrice || checkModel
                        .ShopCommission != model.ShopCommission || checkModel.DisplaySort != model.DisplaySort)
                    {
                        ShopCommodityBLL.Instance.UpdateShopCommodityByCommodityIds(model.Id.ToString(), model.SuggestedPrice, model.ShopCommission, model.DisplaySort);
                    }
                }
                if (!string.IsNullOrEmpty(model.CouponArr))
                {
                    CommodityCouponGiftBLL.Instance.DeleteByCommodityLibId(model.Id);
                    string[] ids = model.CouponArr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    foreach (var item in ids)
                    {
                        var couponArr = item.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                        var id = 0;
                        var quantity = 0;
                        if (!int.TryParse(couponArr[0], out id) || !int.TryParse(couponArr[1], out quantity)) continue;
                        if (quantity > 0)
                        {
                            CommodityCouponGiftBLL.Instance.Add(new CommodityCouponGift() { CouponId = id, Quantity = quantity, BelongToCommodityLibId = model.Id });
                        }
                    }
                }
                return RedirectToAction("List");
            }
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 删除

        [HttpPost]
        public JsonResult Delete()
        {
            string ids = Request["doIds"];
            bool result = _bll.DeleteList(ids);

            //删除平台商品商家店铺关系数据
            ShopCommodityBLL.Instance.DeleteByLanmaSoldCommodityIds(ids);

            return Json(result);
        }

        #endregion

        /// <summary>
        /// 搜索商品
        /// </summary>
        [HttpPost]
        public JsonResult GetCommodityLibList(string keyWords)
        {
            var result = new Result<List<CommodityLib>>();
            var commodityLibList = CommodityLibBLL.Instance.GetListByCommodityName(keyWords);
            if (commodityLibList != null)
            {
                result = new Result<List<CommodityLib>>
                {
                    Status = true,
                    Message = "Success",
                    Data = commodityLibList
                };
            }
            else
            {
                result.Message = "商品不存在！";
            }
            return Json(result);
        }

        /// <summary>
        /// 搜索优惠劵
        /// </summary>
        [HttpPost]
        public JsonResult GetCouponList(string keyWords)
        {
            var result = new Result<List<Coupon>>();
            var couponList = CouponBLL.Instance.GetListByCouponName(keyWords);
            if (couponList != null)
            {
                result = new Result<List<Coupon>>
                {
                    Status = true,
                    Message = "Success",
                    Data = couponList
                };
            }
            else
            {
                result.Message = "优惠劵不存在！";
            }
            return Json(result);
        }

        /// <summary>
        /// 设置批量售卖商品
        /// </summary>
        [HttpPost]
        public JsonResult SelectCommdityId(CommodityLib model)
        {
            var result = new Result<int>();
            var commodityLib = CommodityLibBLL.Instance.GetModel(model.CommodityLibIdByBatch);
            if (commodityLib != null)
            {
                commodityLib.CommodityLibIdByBatch = model.CommodityLibIdByBatch;
                commodityLib.QuantityOfBatchSale = model.QuantityOfBatchSale;
                var isBoool = CommodityLibBLL.Instance.Update(commodityLib);
                result = new Result<int>
                    {
                        Status = true,
                        Message = "Success",
                        Data = isBoool == true ? 1 : 0
                    };
            }
            else
            {
                result.Message = "商品不存在！";
            }
            return Json(result);
        }
        /// <summary>
        /// 所有数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCount()
        {
            var data = _bll.GetTotalCount();
            return Json(data);
        }
        #region Private Functions 自用函数
        private void InitiSet()
        {
            List<SelectListItem> lsBrands = CommodityBrandBLL.Instance.GetModelList().Select(model => new SelectListItem
            {
                Value = model.Id.ToString(),
                Text = model.BrandName
            }).ToList();
            ViewBag.Brands = lsBrands;

            List<SelectListItem> lsCategories =
                CommodityCategoryBLL.Instance.GetModelList().Select(model => new SelectListItem
                {
                    Value = model.Id.ToString(),
                    Text = model.CategoryName
                }).ToList();
            ViewBag.Categories = lsCategories;

            var lsAreas = new List<SelectListItem>
            {
                new SelectListItem {Value = "0", Text = "无"},
            };
            ViewBag.Areas = lsAreas;
        }
        #endregion
    }
}